package com.gugee.ins.data.task.mark.service;

import com.gugee.ins.common.dto.RankTaskParam;
import com.gugee.ins.data.common.msg.InsMarkMessage;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;

/**
 * ins大博主日打点
 * @author huangxin
 */
@Component
@Slf4j
public class InsBloggerMarkDaySvc extends AbstractMarkRankProducerHandler {

    @Autowired
    @Qualifier("insBloggerMarkDayProducer")
    private KafkaTemplate<Long, InsMarkMessage> insBloggerMarkDayProducer;

    /**
     * 执行
     */
    @Override
    public void handleRank(RankTaskParam taskParam) {
        long maxId = objectTotals();
        int startId = 1;
        int endId = taskConfig.getInsBloggerMarkDayPageSize() > 0 ? taskConfig.getInsBloggerMarkDayPageSize() : 1000;
        int page = 1;
        InsMarkMessage insMarkMessage = new InsMarkMessage();
        insMarkMessage.setPageSize(taskConfig.getInsBloggerMarkDayPageSize());
        insMarkMessage.setRetryTimes(taskConfig.getInsBloggerMarkDayRetryTimes());
        insMarkMessage.setRetryLimitTimes(taskConfig.getInsBloggerMarkDayRetryTimes());

        // 判断是否是周日，周日则大博主表的数据都得打点
        // 非周日0，周日1
        long followerCountLimit = getFollowerCountLimit();

        // 循环爬取大博主的id，发送消息打点
        while(endId < maxId || startId == 1){
            try{
                List<Long> uids = insBloggerMainDao.findInsBloggerUidByPages(startId,endId,followerCountLimit);
                if(uids != null && !uids.isEmpty()){
                    insMarkMessage.setUids(uids);
                    insMarkMessage.setPage(page);
                    insBloggerMarkDayProducer.send(taskConfig.getInsMarkDayOnlineTopic(),insMarkMessage);
                }
            }catch (Exception e){
                log.info("ins大博主发送需要日打点的uid 失败 , msg :{}", e.getMessage());
                XxlJobLogger.log("ins大博主发送需要日打点的uid 失败 , msg :{}", e.getMessage());
            }
            page++;
            startId += taskConfig.getInsBloggerMarkDayPageSize();
            endId += taskConfig.getInsBloggerMarkDayPageSize();
        }
    }

    /**
     * 获取最大的id
     * @return
     */
    public long objectTotals() {
        return insBloggerMainDao.getMaxId();
    }

    /**
     * 判断是否是周日，周日则大博主表的数据都得打点
     * @return
     */
    public long getFollowerCountLimit(){
        Calendar calendar = Calendar.getInstance();
        if(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
            return taskConfig.getSysCollectFollowerCount();
        }else {
            return taskConfig.getInsBloggerMainFollowerCountMin();
        }
    }
}
